{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "917cbdbe-4c8f-4fda-ba28-6d0f580db7ed",
   "metadata": {},
   "source": [
    "# Socket TCP 服务端 demo"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ad6916de-7da9-4441-88c8-cbb7a3b69309",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ping\n",
      "ping\n",
      "ping\n",
      "ping\n",
      "ping\n",
      "ping\n",
      "ping\n",
      "ping\n",
      "ping\n"
     ]
    }
   ],
   "source": [
    "import socket\n",
    "import sys\n",
    "import os\n",
    "import time\n",
    "\n",
    "ping_sock = './ping.sock'\n",
    "\n",
    "if os.path.exists(ping_sock):\n",
    "    os.unlink(ping_sock)\n",
    "    \n",
    "sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n",
    "sock.bind(ping_sock)\n",
    "sock.listen(5)\n",
    "conn, clientAddr = sock.accept()\n",
    "try:\n",
    "    while True:\n",
    "        data = conn.recv(10)\n",
    "        print(data.decode())\n",
    "        if data.decode() == 'ping':\n",
    "            conn.send('pong'.encode())\n",
    "except Exception as e:\n",
    "    print(e)\n",
    "    pass\n",
    "finally:\n",
    "    conn.close()\n",
    "    sock.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "80f4c60a-4487-490b-87b5-6b15eda0a38d",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
